package aop

import (
	"bytes"
	"encoding/json"
	"gin-demo/common"
	"gin-demo/container"
	"gin-demo/dao/operate"
	"gin-demo/entity"
	"github.com/gin-gonic/gin"
	"github.com/rs/zerolog/log"
	"time"
)

/**
拦截路由请求信息，记录到日志中
*/
type bodyLogWriter struct {
	gin.ResponseWriter               //响应的写入流
	body               *bytes.Buffer // 暂时的存放数据
}

func (w bodyLogWriter) Write(b []byte) (int, error) {
	w.body.Write(b)
	return w.ResponseWriter.Write(b)
}

func GinBodyLogMiddleware(c *gin.Context) {
	blw := &bodyLogWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer}
	c.Writer = blw
	c.Next()
	//marshal, _ := json.Marshal(blw.body.String())
	//log.Info().Interface("response:", marshal).Send()

	if c.Request.Method != "GET" {
		result := common.Response{}
		err := json.Unmarshal(blw.body.Bytes(), &result)
		if err != nil {
			log.Info().Msg("转换失败")
			return
		}
		// 写入数据库中
		record := &entity.Record{
			Operator:       "admin",
			MethodType:     c.Request.Method,
			StartTime:      time.Now().Unix(),
			Url:            c.Request.RequestURI,
			ReturnCode:     result.Code,
			Message:        result.Message,
			OperateContent: "",
		}
		recordDao := container.Get("recordDao").(operate.RecordDao)
		err = recordDao.Insert(record)
		if err != nil {
			log.Info().Msg("记录写入失败")
		}
	}
}
